import axios from "axios";
import store from "@/store";
import { clearToken } from "./auth";
import { logoutAction } from "@/store/actions/user";
import history from "./history";
import { message } from "antd";
const instance = axios.create({
    baseURL: 'http://toutiao.itheima.net',
    timeout: 5000
})

instance.interceptors.request.use(
    (config) => {
        const state = store.getState()
        if (state.user.token) {
            config.headers.Authorization = `Bearer ${state.user.token}`
        }
        return config
    },
    (error) => Promise.reject(error)
)



instance.interceptors.response.use(
    (response) => {
        return response ? response.data : response
    },
    (error) => {
        if (error.response?.status === 401) {
            clearToken()
            store.dispatch(logoutAction())
            history.push({
                pathname: '/login',
                state: { from: history.location.pathname }
            })
            message.warning('登录失效,请重新登录')
        }
        return Promise.reject(error)
    }
)

export default instance